var soundList = ['Do_aigu', 'Do_grave', 'Do_Medium', 'Fa_aigu', 'Fa_grave', 'Fa_Medium', 'La-aigu', 'La_grave', 'La_medium', 'Mi_aigu', 'Mi_grave', 'Mi_medium', 'Re_Aigu', 'Re_grave', 'Re_grave_2', 'Re_Medium', 'Si_aigu', 'Si_grave', 'Si_Medium', 'Sol_aigu', 'Sol_grave', 'Sol_medium'];
var soundNumber = soundList.length;
var sounds = new Array();

var mouseDuration;
var mouseDownTime;
var mouseAutomationTimer;

var textsFR = ['Impossible de charger les phrases.', 'no'];
var textsEN = ['Can`t load sentences.', 'non'];
var textEN = textsEN[0];
var textFR = textsFR[0];

var modeAuto = true;
var selectedSpan = null;

var sound_on = true;
var wave = 0;
var index = 0;

var determinants = ["d'un", "d'une", "d’un", "d’une", 'un', 'une', 'le', 'la', "l'", 'mon', 'ton', 'son', 'ma', 'ta', 'sa', 'cet', 'cette'];

function trim(myString) {
	return myString.replace(/^\s+/g, '').replace(/\s+$/g, '')
}

function appendToCloud(phrase) {
	var h = $(document).height() - 270 - $('#mainPhrase').height();
	$('#cloud').append('<div class="derive" style="top: ' + h + 'px;">' + phrase + '</div>');
	moveClouds();
}

function moveClouds() {
	var h = $(document).height() - 270 - $('#mainPhrase').height();

	var n = $('#cloud div').length;
	$.each($('#cloud div'), function (i, el) {
		wave++;
		el = $(el);

		newTop = i * (h / 7);

		el.animate({
			top: newTop + 'px',
			opacity: 0.1 + (i / 7),
			fontSize: 10 + (i / 7) * 10,
			left: 100 * Math.sin(wave)
		}, 'slow');
		if (i > 5) {
			$('#cloud div:first').remove();
		}
	});

}

function morphText() {
	var reg = new RegExp("[ ,;\.\r\n]+", "g");
	var wholeText = '';
	$.each($('#mainPhrase').text().split(reg), function (i, el) {
		wholeText = wholeText + ' <span>' + trim(el) + '</span>';
	});

	wholeText = wholeText.replace(/<span>\*([^\<]*)\*<\/span>/g, "$1");
	wholeText = wholeText.replace(/_/g, ' ')
	$('#mainPhrase').html(wholeText);
}


function Exchange(e) {
	elt = $(e).text();
	previous = $(e).prev().text();
	if (elt.length > 3 && !$(e).hasClass('loading')) {
		$(e).addClass('loading');
		
		$.ajax({
			url: "getSynonyme.php",
			dataType: 'json',
			data: {
				word: encodeURIComponent(elt),
				previous: encodeURIComponent(previous),
				lang: lang
			},
			success: function (data) {
				$(e).removeClass('loading');
				var syns = data.syns;
				if (syns.length != 0) {
					var len = syns.length;
					var rand = Math.floor(Math.random() * len);
					
					previous = $(e).prev().text();
					if (determinants.indexOf(previous) != -1) {
						$(e).prev().remove();
					}
					syns[rand] = '<span>' + syns[rand] + '</span>';
					syns[rand] = syns[rand].replace(/\+/g, '</span> <span>');
					syns[rand] = syns[rand].replace(/_/g, ' ');
					$(e).after(syns[rand]).remove();
					playRandomNote();
				}
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				console.log(textStatus, errorThrown);
				$(e).removeClass('loading');
				playRandomNote();
			}
		});
	}
}


function Choose(e) {
	if (selectedSpan == null) {
		elt = $(e).text();
		previous = $(e).prev().text();
		if (elt.length > 3 && !$(e).hasClass('loading')) {
			$(e).addClass('loading');
			
			$.ajax({
				url: "getSynonyme.php",
				dataType: 'json',
				data: {
					word: encodeURIComponent(elt),
					lang: lang
				},
				success: function (data) {
					$(e).removeClass('loading');
					var syns = data.syns;
					if (syns.length != 0) {
						var len = syns.length;

						var ul = '<ul id="ul">';
						if (syns.length >= 7)
							for (i = 0; i < 7; i++)
							{
								ul += '<li>' + syns[i] + '</li>';
							}
						else
							$.each(syns, function (i, el) {
								ul += '<li>' + syns[i] + '</li>';
							});
						ul += '</ul>';
						$("#selector").html(ul);
						$("#ul").css({
							'position': 'absolute',
							'top': $(e).offset().top - $("#ul").height() / 2,
							'left': $(e).offset().left
						});
						selectedSpan = $(e);
						$('#ul li').click(function () {
							$("#mainPhrase").unbind("mouseenter");
							Select(this);
							playRandomNote();
						});
					}
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
					$(e).removeClass('loading');
				}
			});
		}
	}
}


function Select(e) {
	$(selectedSpan).html($(e).text());
	$('#ul').remove();
	selectedSpan = null;
}

function fetchPhrases() {
	$.ajax({
		url: "phrases." + lang + ".txt",
		dataType: 'txt',
		success: function (data) {
			console.log(lang);
			if (lang == 'FR') {
				textsFR = data.responseText.split("\n");
				$('#mainPhrase').html(textsFR[index]);
			} else if (lang == 'EN') {
				textsEN = data.responseText.split("\n");
				$('#mainPhrase').html(textsEN[index]);
			}
			morphText();
			index++;
		},
		error: function (data) {
			if (lang == 'FR') {
				textsFR = data.responseText.split("\n");
				$('#mainPhrase').html(textsFR[index]);
			} else if (lang == 'EN') {
				textsEN = data.responseText.split("\n");
				$('#mainPhrase').html(textsEN[index]);
			}
			morphText();
			index++;
		}
	});
}

function playRandomNote() {
	if (sound_on) {
		i = $.random(soundNumber);
		sounds[i].play();
	}
}

function resize() {
	moveClouds();
}

$('#index').ready(function (event) {
	for (var i = 0; i < soundList.length; i++) {
		sounds.push(new buzz.sound("/sounds/" + soundList[i], {
			formats: ["ogg", "mp3"],
			preload: true
		}));
	}

	var sound_background = new buzz.sound("/sounds/changerTout", {
		formats: ["ogg", "mp3"],
		preload: true,
		autoplay: true,
		loop: true
	});

	$(window).resize(function () {
		resize();
	});
	console.log(userInput);
	if (userInput == '') {
		fetchPhrases();
	} else {
		$('#mainPhrase').html(userInput);
		morphText();
	}
	
	// RESPONSABLE DU COMPORTEMENT DES BOUTONS DE CONTROLE (changer tout, suivant, sound, input)
	$('#input').click(function () {  
		$('#mainPhrase').empty();
		$('#mainPhrase').html('<input type="text" id="userInput"></input><input id="userInputSubmit" class="submit" type="submit"/>');
		$('#userInput').focus();
		$('#userInputSubmit').click(function () {
			userInput = $('#mainPhrase').html($('#userInput').val());
			morphText();
		});
		return false;
	});
	
	$('#form').submit(function () {
		$('#mainPhrase').html($('#userInput').val());
		morphText();
		return false;
	});

	$('#sound').click(function () {
		if (sound_on) {
			sound_background.pause();
			$('#sound').addClass('off');
		} else {
			sound_background.play();
			$('#sound').removeClass('off');
		}
		sound_on = !sound_on;
	});
	var conf = false;
	$('#conf').click(function () {
		if (conf) {
			$('#confpanel').fadeOut();
		} else {
			$('#confpanel').fadeIn();
		}
		conf = !conf;
	});
	$('#next').click(function () {
		appendToCloud($('#mainPhrase').text());
		$('#mainPhrase').slideUp(250, function () {
			if (lang == 'FR') {
				if (index >= textsFR.length) index = 0;
			} else {
				if (index >= textsEN.length) index = 0;
			}
			if (lang == 'FR') {
				$('#mainPhrase').html(textsFR[index]);
			} else {
				$('#mainPhrase').html(textsEN[index]);
			}
			morphText();
			$('#mainPhrase').slideDown();
			index++;
		});
	});

	$('#mode').click(function () {
		modeAuto = !modeAuto;
		if (modeAuto) {
			$('#modeID').html("Auto");
		} else {
			$('#modeID').html("Manuel / Manual");
		}
	});

	$('#all').click(function () {
		$('#ul').remove();
		selectedSpan = null;
		$.each($('#mainPhrase span'), function (i, e) {
			Exchange(e);
		});
		appendToCloud($('#mainPhrase').text());
	});

	$('#lang').click(function () {
		$('body').removeClass(lang);
		if (lang == 'FR') {
			lang = 'EN';
			$('#mainPhrase').html(textEN);
			morphText();
		} else {
			lang = 'FR';
			$('#mainPhrase').html(textFR);
			morphText();
		}
		$('body').addClass(lang);
		$('#langID').html(lang);
	});


	// RESPONSABLE DES INTERRACTIONS QUAND ON CLIQUE SUR LES MOTS
	$('#mainPhrase span').live('mousedown', function () {
		mouseDownTime = (new Date()).getTime();
		elt = this;
		mouseAutomationTimer = window.setTimeout(function () {
			Choose(elt)
		}, 750);
	});

	/* $('#mainPhrase span').live('mouseup', function () {
		clearTimeout(mouseAutomationTimer);
		mouseDuration = (new Date()).getTime() - mouseDownTime;
		if (mouseDuration < 500) {
			phrase = $('#mainPhrase').text();
			appendToCloud(phrase);
			if (modeAuto) {
				Exchange(this);
			} else {
				Choose(this);
			}
		}
	}); */
	
	/*
	[PIERRE] adaptation de la fonction précédente pour les events de type tap
	*/
	$('#mainPhrase span').bind('tap', function () {
		phrase = $('#mainPhrase').text();
		appendToCloud(phrase);
		if (modeAuto) {
			Exchange(this);
		} else {
			Choose(this);
		}
	});
	//[PIERRE] fin adaptation de la fonction précédente pour les events de type tap
	
	/*
	[PIERRE] fonction pour taphold
	*/
	$('#mainPhrase span').bind('taphold', function () {
		Choose(this);
	});
	//	[PIERRE] fin fonction pour taphold

// RESPONSABLE DES INTERRACTIONS QUAND ON CLIQUE SUR LES MOTS [FIN]

});

jQuery.fn.extend({
	disableSelection: function () {
		return this.each(function () {
			this.onselectstart = function () {
				return false;
			};
			this.unselectable = "on";
			jQuery(this).css('user-select', 'none');
			jQuery(this).css('-o-user-select', 'none');
			jQuery(this).css('-moz-user-select', 'none');
			jQuery(this).css('-khtml-user-select', 'none');
			jQuery(this).css('-webkit-user-select', 'none');
		});
	}
});

jQuery.extend({
	random: function (X) {
		return Math.floor(X * (Math.random() % 1));
	},
	randomBetween: function (MinV, MaxV) {
		return MinV + jQuery.random(MaxV - MinV + 1);
	}
});
